import { defineStore } from 'pinia';
import axios from 'axios';

export const userStore = defineStore('user', {
  state: () => ({
    users: [],
    currentUser: null,
    loading: false,
    error: null,
    pagination: {
      currentPage: 1,
      totalPages: 1,
      itemsPerPage: 10
    }
  }),

  actions: {
    // 获取所有用户（管理员）
    async getUsers(page = 1, itemsPerPage = 10) {
      this.loading = true;
      this.error = null;
      try {
        const params = {
          page,
          itemsPerPage
        };
        
        const response = await axios.get('/users', { params });
        this.users = response.data.users;
        this.pagination = response.data.pagination;
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '获取用户列表失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取单个用户详情（管理员）
    async getUserById(id) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.get(`/users/${id}`);
        this.currentUser = response.data;
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '获取用户详情失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新用户信息（管理员）
    async updateUser(id, userData) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.put(`/users/${id}`, userData);
        await this.getUsers(); // 刷新用户列表
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '更新用户信息失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 删除用户（管理员）
    async deleteUser(id) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.delete(`/users/${id}`);
        await this.getUsers(); // 刷新用户列表
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '删除用户失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 搜索用户（管理员）
    async searchUsers(query, page = 1, itemsPerPage = 10) {
      this.loading = true;
      this.error = null;
      try {
        const params = {
          query,
          page,
          itemsPerPage
        };
        
        const response = await axios.get('/users/search', { params });
        this.users = response.data.users;
        this.pagination = response.data.pagination;
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '搜索用户失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 清除错误信息
    clearError() {
      this.error = null;
    },

    // 清除当前用户
    clearCurrentUser() {
      this.currentUser = null;
    }
  },

  getters: {
    // 获取活跃用户数量
    activeUsersCount: (state) => {
      return state.users.filter(user => user.isActive !== false).length;
    },

    // 获取管理员用户数量
    adminUsersCount: (state) => {
      return state.users.filter(user => user.role === 'admin').length;
    },

    // 获取普通用户数量
    regularUsersCount: (state) => {
      return state.users.filter(user => user.role === 'user').length;
    }
  }
});